import { defineStore } from "pinia";
import { useTabStore } from "./tab";

export const useAuthStore = defineStore({
    id: "auth",
    state: () => {
        return {
            token: undefined,
            userProfile: undefined,
        };
    },
    getters: {
    },
    actions: {
        authenticate(data) {
            this.token = data.token;
        },
        setUserProfile(userProfile) {
            if (userProfile.menus) {
                const flat = (tree) => {
                    let res = [];
                    tree.forEach(item => {
                        res.push(item)
                        item.children && res.push(...flat(item.children))
                    })
                    return res;
                };
                userProfile.menuList = flat(userProfile.menus);
                userProfile.menuIdDict = {};
                userProfile.menuPathDict = {};
                userProfile.menuList.forEach(item => {
                    userProfile.menuIdDict[item.id] = item;
                    if (item.type == 'MENU') {
                        userProfile.menuPathDict[item.route] = item;
                    }
                });
            }
            this.userProfile = userProfile;
        },
        unAuthenticate() {
            this.token = undefined;
            this.userProfile = undefined;
            const tabStore = useTabStore();
            tabStore.clear();
        }
    },
    // 开启认证信息持久化存储，保存在sessionStorage，浏览器窗口关闭后清空
    persist: {
        key: "fast_alden_auth",
        storage: sessionStorage,
    }
});

export default useAuthStore;